#!/usr/bin/env node

const { execSync } = require('child_process');
const path = require('path');

// 获取命令行参数
const args = process.argv.slice(2);
const migrationName = args[0];

if (!migrationName) {
  console.log('❌ 错误: 请提供迁移文件名称');
  console.log('');
  console.log('使用方法:');
  console.log('  node scripts/generate-migration.js <迁移名称>');
  console.log('');
  console.log('示例:');
  console.log('  node scripts/generate-migration.js InitialMigration');
  console.log('  node scripts/generate-migration.js CreateUserTable');
  console.log('  node scripts/generate-migration.js AddUserFields');
  console.log('');
  console.log('或者使用预设命令:');
  console.log('  npm run migration:generate:init');
  console.log('  npm run migration:generate:user');
  process.exit(1);
}

// 构建迁移文件路径
const migrationPath = `migrations/${migrationName}`;

try {
  console.log(`🔄 正在生成迁移文件: ${migrationPath}`);
  
  // 执行TypeORM迁移生成命令
  const command = `npx typeorm-ts-node-commonjs migration:generate -d src/config/database.config.ts ${migrationPath}`;
  
  execSync(command, { 
    stdio: 'inherit',
    cwd: process.cwd()
  });
  
  console.log(`✅ 迁移文件生成成功: ${migrationPath}`);
  console.log('');
  console.log('下一步:');
  console.log('  1. 检查生成的迁移文件');
  console.log('  2. 运行迁移: npm run migration:run');
  
} catch (error) {
  console.error('❌ 迁移文件生成失败:', error.message);
  console.log('');
  console.log('可能的解决方案:');
  console.log('  1. 检查数据库连接: npm run db:check');
  console.log('  2. 确保数据库服务正在运行');
  console.log('  3. 验证数据库配置');
  process.exit(1);
} 